package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/user")
@Controller
public class UserController {

    @Reference
    UserService service ;

    @RequestMapping("/loginSuccess")
    public String loginSuccess(){

        return "redirect:http://localhost:83/pages/main.html";
    }

    @RequestMapping("/loginFail")
    public String loginFail(){

        return "redirect:http://localhost:83/login.html?param=loginFail";
    }



    @RequestMapping("/findUsername")
    @ResponseBody
    public Result findUsername(){

        try {
            //获取安全框架的上下文对象
            SecurityContext context = SecurityContextHolder.getContext();
            //获取认证对象
            Authentication authentication = context.getAuthentication();
            //获取用户对象
            Object principal = authentication.getPrincipal();
            User user = (User) principal;
            String username = user.getUsername();
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS,username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_USERNAME_FAIL);
        }

    }

    @RequestMapping("/queryId")
    @ResponseBody
    public Result queryId() {
        try {
            //获取安全框架的上下文对象
            SecurityContext context = SecurityContextHolder.getContext();
            //获取认证对象
            Authentication authentication = context.getAuthentication();
            //获取用户对象
            Object principal = authentication.getPrincipal();
            User user = (User) principal;
            String username = user.getUsername();
            Integer userId = service.findIdByUsername(username);
//            //根据userid查menu
            List<Map<String,Object>> menuList = service.showMenuByUserId(userId);
//            return new Result(true,MessageConst.GET_USERNAME_SUCCESS,userId);
            return new Result(true, MessageConst.GET_MENU_SUCCESS, menuList);
        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result(false,MessageConst.GET_USERNAME_FAIL);
            return new Result(false, MessageConst.GET_MENU_FAIL);

        }
    }

}

